package com.caozhen.manage.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.caozhen.manage.response.Response;

@Controller
public class LoginController extends BaseController {

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public Response doLogin(String userName, String password, HttpServletRequest request) {
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(false);
        Subject subject = SecurityUtils.getSubject();
        String errorMsg = "";
        try {
            subject.login(token);
        } catch (UnknownAccountException ex) {
            ex.printStackTrace();
            errorMsg = "没有找到该用户名！";
        } catch (IncorrectCredentialsException ex) {
            ex.printStackTrace();
            errorMsg = "用户名、密码不正确！";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            errorMsg = "其他的登录错误！";
        }
        if(subject.isAuthenticated()){
            return Response.getSuccess();
        }
        return Response.getError(Response.ERROR_CODE, errorMsg);
    }
}
